package com.ljh.nio.c3;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.ArrayList;
import java.util.List;

import static com.ljh.nio.c1.ByteBufferUtil.debugRead;

/**
 * @author: Themberfue
 * @date: 2025/5/26 14:35
 * @description:
 */
public class ServerBlocked {
    private static final Logger log = LoggerFactory.getLogger(ServerBlocked.class);

    public static void main(String[] args) throws IOException {
        // TODO 0. 创建缓冲区
        ByteBuffer buffer = ByteBuffer.allocate(16);

        // TODO 1. 创建服务器
        ServerSocketChannel ssc = ServerSocketChannel.open();

        // TODO 2. 绑定端口
        ssc.bind(new InetSocketAddress(8080));

        // TODO 3. 接收来自的客户端的连接
        List<SocketChannel> channels = new ArrayList<>();
        while (true) {
            log.debug("connecting...");
            // TODO 4. 接收到一个客户端的连接（accept 是一个阻塞的方法，若没有连接，则阻塞在这里）
            SocketChannel sc = ssc.accept(); // ! 阻塞意味着，线程停止运行
            log.debug("connected... {}", sc);
            // TODO 5. 添加到连接队列
            channels.add(sc);
            for (SocketChannel channel : channels) {
                log.debug("before read... {}", channel);
                // TODO 6. 将客户端请求的数据读入缓冲区
                channel.read(buffer); // ! 同样是阻塞的方法，阻塞意味着，线程停止运行
                buffer.flip();
                debugRead(buffer);
                buffer.clear();
                log.debug("after read... {}", channel);
            }
        }
    }
}
